import hashlib
from datetime import datetime
from typing import Annotated, Union

import jwt

from fastapi import APIRouter, Depends, Request

from api.internal.status import Status
from lib import utils
from service.api_service import users as userService
from config import appSettings
from service.api_service.ai import base64_encode_img
from service.api_service.users import UsersService
from .model.user_model import User, WxLoginRequest, WxLoginResponse
from ..dependencies import get_current_user
from ..internal import response

from slowapi import Limiter
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)

router = APIRouter(
    prefix="/users",
    tags=["users"],
    # dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)


@router.post("/wx_login")
async def wx_login(login_info: WxLoginRequest):
    user_info, err = UsersService().wx_user_login(
        login_info.js_code, login_info.invite_code, nick_name="微信用户"
    )
    if err is not None:
        print(err)
        return response.failure()
    # jwt加密
    print(user_info)
    message = {
        "user_id": user_info.id,
        "nick_name": user_info.nick_name,
        "js_code": user_info.wx_js_code,
        "open_id": user_info.wx_open_id,
        "invite_code": user_info.invite_code,
        "iat": int(datetime.now().timestamp()),
        "exp": int(datetime.now().timestamp() + appSettings.jwt_expired * 60),
    }
    authorization = jwt.encode(
        message, appSettings.jwt_secret_key, appSettings.jwt_algorithm
    )
    print(authorization)
    author_solt = authorization + appSettings.jwt_secret_key
    token = hashlib.md5(author_solt.encode()).hexdigest()
    resp = WxLoginResponse(
        expires_in=appSettings.jwt_expired * 60,
        authorization=authorization,
        token=token,
        invite_code=user_info.invite_code,
    )
    print(resp.model_dump_json)
    return response.success(resp)


@router.get("/profile")
async def get_profile(request: Request, user: User = Depends(get_current_user)):
    # 获取用户信息
    user_info = UsersService().profile(user.user_id)
    return response.success(user_info)


@router.get("/token_refresh")
async def token_refresh(request: Request, user: User = Depends(get_current_user)):
    # 校验token是否失效
    author = userService.token_refresh(user)
    author_salt = author + appSettings.jwt_secret_key
    token = hashlib.md5(author_salt.encode()).hexdigest()
    resp = WxLoginResponse(
        expires_in=appSettings.jwt_expired * 60,
        authorization=author,
        token=token,
        invite_code=user.invite_code,
    )
    return response.success(resp)


@router.get("/order_list")
async def order_list(
    request: Request,
    user: User = Depends(get_current_user),
    page: int = 1,
    size: int = 20,
):
    # 获取用户订单
    orders = userService.UsersService().order_list(user.user_id, page, size)
    return response.success(orders)


@router.get("/order/{order_id}")
@limiter.limit("20/minute")
async def order_detail(
    request: Request,
    user: User = Depends(get_current_user),
    order_id: Union[int, None] = None,
):
    if order_id is None:
        return response.params_error()
    # 获取订单详情 TODO 后续优化redis 同步
    order = userService.UsersService().order_detail(user.user_id, order_id)
    print(order)
    if order is None:
        return response.to_json(code=Status.ORDDER_NOT_EXIST)
    res = {
        "status": order.status,
        "alpha": None,
    }
    if order.status == 2:
        # 处理完成 读取照片文件返回给客户端
        res["alpha"] = base64_encode_img(order.out_pic)
    return response.success(res)
